﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Data;
using System.Data.SQLite;

/*
 * Author:Conis
 * Date:
 * Description:数据库访问
 */

namespace Conis.Squirrel.SqlBuilder.SQLite
{
    /// <summary>
    /// 数据库访问
    /// </summary>
    public class DataAccess: BaseDataAccess
    {

        public DataAccess(BaseSqlFactory sqlFactory, string tableName, string primaryKey):
            base(sqlFactory, tableName, primaryKey) { }

        /// <summary>
        /// 创建一个新的参数
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        protected override IDataParameter GetParameter(string key, object value)
        {
            return new SQLiteParameter(key, value);
        }

        /// <summary>
        /// 获取单页的数据集
        /// </summary>
        /// <param name="pagination"></param>
        /// <param name="condition"></param>
        /// <param name="fields"></param>
        /// <param name="orderBy"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        protected override DataTable GetSinglePage(Pagination pagination, string condition, string fields, string orderBy, params IDataParameter[] parameters)
        {
            string sql;
            int startIndex = PaginationHelper.StartIndex(pagination.PageIndex, pagination.PageSize);
            //取得当前分页的数据
            sql = "SELECT {0} FROM {1}{2}{3} LIMIT {4}, {5}";
            sql = string.Format(sql, fields, this.TableName, condition, orderBy, startIndex, pagination.PageSize);
            return this.SqlFactory.ExecuteSql.GetDataTable(sql, CommandType.Text, parameters);
        }

        /// <summary>
        /// 插入一条记录，并获取刚刚插入的主键
        /// </summary>
        /// <param name="nameValue">保存字段与值的Hashtable</param>
        /// <param name="ignoreNull">是否忽略Null</param>
        /// <param name="ignorePrimaryKey">是否忽略主键</param>
        /// <returns>返回刚刚插入的主键</returns>
        public override object Insert(Hashtable nameValue, bool ignoreNull, bool ignorePrimaryKey)
        {
            IDataParameter[] parameters;
            string sql = this.GetInsertSql(nameValue, ignoreNull, ignorePrimaryKey, out parameters);
            sql += "; SELECT LAST_INSERT_ROWID();";
            object result = this.SqlFactory.ExecuteSql.ExecuteScalar(sql, CommandType.Text, parameters);
            return result;
        }
    }
}
